package com.dmbjz.serivice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmbjz.entity.SecurityUser;
import com.dmbjz.entity.Users;
import com.dmbjz.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/*自定义登录方式*/
@Service("detailsService")
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /*查询数据库*/
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);

        /*判断*/
        if (users == null) {
            throw new UsernameNotFoundException("用户不存在");
        }


        /* 设置用户具有的权限和 boss 角色 */
        //List<GrantedAuthority> authsList = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_worker,ROLE_javase,worker:java:create,worker:java:del");
        //return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()),authsList);

        /*自定义用户登录验证Filter需要返回string的权限list*/
        users.setPassword( new BCryptPasswordEncoder().encode(users.getPassword()));
        List<String> authList = Arrays.asList("admin","ROLE_worker","ROLE_javase","worker:java:create","worker:java:del");
        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(users);
        securityUser.setPermissionValueList(authList);
        return securityUser;

    }


}
